package com.bw.day03.xq

import android.R.attr.bitmap
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.ActionBar.LayoutParams
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bw.base.net.entity.XqEntity
import com.bw.base.net.mvvm.BaseActivity
import com.bw.base.net.param.OrderDetail
import com.bw.base.net.param.ParamPreOrder
import com.bw.day03.R
import com.bw.day03.adapter.CommentAdapter
import com.bw.day03.databinding.ActivityXqBinding
import com.bw.day03.room.AppDBUtlis
import com.bw.day03.room.Comment
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.utils.UmengText
import com.youth.banner.loader.ImageLoader
import java.text.SimpleDateFormat

@Route(path = "/app/XqActivity")
class XqActivity : BaseActivity<ActivityXqBinding, XqViewModel>() {
    val list=mutableListOf<String>()
    var attrId=""
    var imgurl=""
    @Autowired
    @JvmField
    var goodsId=1
     var userCollect: Boolean = false
    lateinit var dialog: AlertDialog
    override fun initView() {
        requestPermissions(arrayOf("android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"),100)
        ARouter.getInstance().inject(this)
        viewModel.xq(goodsId,"normal")
        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.addCar.setOnClickListener {
            viewModel.addCar(1,attrId,goodsId)
        }
        //评论
        binding.tvReply.setOnClickListener {
            val popupWindow= PopupWindow()
            var inflate = LayoutInflater.from(this).inflate(R.layout.item_pop, null)
            val commentAdapter= CommentAdapter()
            var rv = inflate.findViewById<RecyclerView>(R.id.rv_comment)
            rv.adapter=commentAdapter
            rv.layoutManager= LinearLayoutManager(this)
            var queryAll = AppDBUtlis.getDB().getCommentDao().queryAll(goodsId)
            commentAdapter.data.clear()
            commentAdapter.data.addAll(queryAll)
            commentAdapter.notifyDataSetChanged()
            inflate.findViewById<Button>(R.id.send).setOnClickListener {
                var toString = inflate.findViewById<EditText>(R.id.et).text.toString()
                val comment= Comment(0, SPUtils.getInstance().getString("phone"),"",toString,
                    SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis()),goodsId)
                AppDBUtlis.getDB().getCommentDao().insert(comment)
                inflate.findViewById<EditText>(R.id.et).setText("")
                commentAdapter.data.add(comment)
                commentAdapter.notifyDataSetChanged()
            }
            //搜索
            val sv = inflate.findViewById<SearchView>(R.id.sv)
            sv.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
                override fun onQueryTextSubmit(query: String?): Boolean {
                    if (query!=null){
                        val query1 = AppDBUtlis.getDB().getCommentDao().query(query, goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query1)
                        commentAdapter.notifyDataSetChanged()
                    }else{
                        var queryAll = AppDBUtlis.getDB().getCommentDao().queryAll(goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(queryAll)
                        commentAdapter.notifyDataSetChanged()
                    }
                    return false
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    if (newText!=null){
                        val query1 = AppDBUtlis.getDB().getCommentDao().query(newText, goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query1)
                        commentAdapter.notifyDataSetChanged()
                    }else{
                        var queryAll = AppDBUtlis.getDB().getCommentDao().queryAll(goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(queryAll)
                        commentAdapter.notifyDataSetChanged()
                    }
                    return false
                }
            })

            popupWindow.width= LayoutParams.MATCH_PARENT
            popupWindow.height=1000
            popupWindow.contentView=inflate
            popupWindow.isOutsideTouchable=true
            popupWindow.isFocusable=true
            popupWindow.showAtLocation(binding.tvReply, Gravity.BOTTOM,0,0)
        }

        binding.ivShare.setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.item_dlog, null)
            //显示图片

            //生成图片
            val encodeBitmap =
                BarcodeEncoder().encodeBitmap(imgurl, BarcodeFormat.QR_CODE, 200, 200)
            view.findViewById<ImageView>(R.id.iv).setImageBitmap(encodeBitmap)
            view.findViewById<TextView>(R.id.no).setOnClickListener {
                dialog.dismiss()
            }
            view.findViewById<Button>(R.id.yes).setOnClickListener {
                dialog.dismiss()
                val image: UMImage = UMImage(this, encodeBitmap) //bitmap文件
                ShareAction(this).withText("hello").withMedia(image)
                    .setDisplayList(SHARE_MEDIA.QQ)
                    .setCallback(object : UMShareListener{
                        override fun onStart(p0: SHARE_MEDIA?) {

                        }

                        override fun onResult(p0: SHARE_MEDIA?) {

                        }

                        override fun onError(
                            p0: SHARE_MEDIA?,
                            p1: Throwable?
                        ) {
                            ToastUtils.showLong(p1?.message)
                        }

                        override fun onCancel(p0: SHARE_MEDIA?) {

                        }
                    })
                    .open();
            }
            dialog = AlertDialog.Builder(this)
                .setTitle("提示")
                .setView(view)
                .create()
            dialog.show()

        }
        binding.ivShoucang.setOnClickListener {
            if (userCollect==false){
                viewModel.love("store",goodsId)
                userCollect=true
                binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_24)

            }else{
                viewModel.noLove(goodsId)
                userCollect=false
                binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_border_24)
            }
        }
        binding.tvGocar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }
        binding.ivGocar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }
        binding.buyNow.setOnClickListener {
            val paramPreOrder= ParamPreOrder()
            paramPreOrder.preOrderType="buyNow"
            var list=mutableListOf<OrderDetail>()
            var orderDetail= OrderDetail()
            orderDetail.productId=goodsId
            orderDetail.attrValueId=attrId.toInt()
            orderDetail.productNum=1
            list.add(orderDetail)
            paramPreOrder.orderDetails=list
            viewModel.preOrder(paramPreOrder)
        }
    }

    override fun initData() {
        viewModel.xqSuccess.observe(this){
            if (it.code==200){
                userCollect=it.data.userCollect
                binding.info=it.data.productInfo
                binding.tvSelected.text="已选择：${it.data.productValue.keys.toList()[0]}"//
                attrId=it.data.productValue.values.toList()[0].id.toString()//
                imgurl=it.data.productInfo.image
                list.add(it.data.productInfo.image)
                list.add(it.data.productInfo.image)
                binding.banner.setImages(list)
                    .setImageLoader(object : ImageLoader(){
                        override fun displayImage(
                            context: Context,
                            path: Any?,
                            imageView: ImageView
                        ) {
                            Glide.with(context).load(path).into(imageView)
                        }
                    }).start()
              //  binding.vv.setVideoPath("URL")
             //   binding.vv.setMediaController(MediaController(this))

                    if (it.data.userCollect==true){
                        binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_24)
                    }else{
                        binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_border_24)
                    }


            }else{
                ToastUtils.showLong(it.message)
            }

        }
        viewModel.addSuccess.observe(this){
            if (it.code==200){
                ToastUtils.showLong("添加成功")
                val imageView= ImageView(this)
                val layoutParams=LayoutParams(200,200)
                imageView.layoutParams=layoutParams
                Glide.with(this).load(imgurl).into(imageView)
                binding.main.addView(imageView)
                var width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()
                val translationX =
                    ObjectAnimator.ofFloat(imageView, "translationX",0f, width, width * 2 / 3)
                val translationY =
                        ObjectAnimator.ofFloat(imageView, "translationY",0f, height)
                val animatorSet = AnimatorSet()
                animatorSet.duration=2000
                animatorSet.play(translationX).with(translationY)
                animatorSet.start()
                animatorSet.addListener(object : Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.main.removeView(imageView)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.loveSuccess.observe(this){
            if (it.code==200){
                ToastUtils.showLong("收藏成功")

               // binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_24)

            }
        }
        viewModel.noLoveSuccess.observe(this){
            if (it.code==200){
                ToastUtils.showLong("取消收藏成功")
               // binding.ivShoucang.setImageResource(R.drawable.baseline_favorite_border_24)
            }
        }

        viewModel.preSuccess.observe(this){
            if (it.code==200){
              //  ToastUtils.showLong(it.data.preOrderNo)
                ARouter.getInstance().build("/app/CreateOrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
    }

    override fun getViewModel(): Class<XqViewModel> = XqViewModel::class.java

    override fun getLayoutId(): Int = R.layout.activity_xq
}